package hn.cch.thymeleaf.service;

import org.neo4j.ogm.cypher.Filters;
import org.neo4j.ogm.cypher.query.Pagination;
import org.neo4j.ogm.cypher.query.SortOrder;
import org.neo4j.ogm.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * 分页处理
 * T(泛型)
 *
 * @author CCH
 * @version 2018.07.11
 */
@Service
public class PageService<T> {

    @Autowired
    private Session session;


    public Page<T> findAll(Class<T> clazz, Filters filters, Pageable pageable) {
        SortOrder sortOrder = convertOrder(pageable.getSort());
        Pagination pagination = new Pagination(pageable.getPageNumber(),
                pageable.getPageSize());
        Collection collection = this.session.loadAll(clazz, filters,
                sortOrder, pagination, 1);
        long total = this.session.loadAll(clazz, filters).size();
        return new PageImpl(new ArrayList(collection), pageable, total);
    }


    private SortOrder convertOrder(Sort sort) {
        SortOrder sortOrder = new SortOrder();
        if (sort != null) {
            Iterator iterator = sort.iterator();
            while (iterator.hasNext()) {
                Sort.Order order = (Sort.Order) iterator.next();
                if (order.isAscending()) {
                    sortOrder.add(new String[]{order.getProperty()});
                } else {
                    sortOrder.add(SortOrder.Direction.DESC, new
                            String[]{order.getProperty()});
                }
            }
        }
        return sortOrder;
    }
}
